<template>
  <view class="edit-goods" v-if="goodsInfo">
    <view class="popup-title">
      {{goodsInfo.goods_name}}
    </view>
    <view class="edit-goods-center flex">
      <view class="edit-goods-center-left" @click="onFocus('')">
        <u--form labelPosition="left" :model="goodsInfo" ref="form1" labelWidth="120">
          <u-form-item :class="{active:curFocus==='goods_stock'}" label="库存" prop="goods_stock" border="none"
            :borderBottom="false" ref="item1">
            <view class="input disabled" :class="{active:curFocus==='goods_stock'}">
              <text v-if="goods.is_temporary_goods==='是'">无限</text>
              <text v-else>{{goodsInfo.goods_stock||''}}</text>
            </view>
          </u-form-item>
          <u-form-item :class="{active:curFocus==='amount'}" label="数量" prop="amount" border="none"
            :borderBottom="false" ref="item1">
            <view class="input" :class="{active:curFocus==='amount'}" @click.stop="onFocus('amount')">
              {{goodsInfo.amount||''}}
            </view>
          </u-form-item>
          <u-form-item :class="{active:curFocus==='scribing_price'}" label="原售价" prop="scribing_price" border="none"
            :borderBottom="false" ref="item3">
            <view class="input disabled">
              <text class="content" v-if="goods.is_temporary_goods==='是'">0元</text>
              <text class="content" v-else> {{goodsInfo._origin_price||'0'}}元</text>
            </view>
          </u-form-item>
          <u-form-item :class="{active:curFocus==='sale_price'}" label="现售价" prop="sale_price" border="none"
            :borderBottom="false" ref="item2">
            <view class="input" :class="{active:curFocus==='sale_price',disabled:allowChangePrice===false}"
              @click.stop="onFocus('sale_price')">
              <text class="content" v-if="goodsInfo.sale_price===0"> 0</text>
              <text class="content" v-else> {{goodsInfo.sale_price||''}}</text>
              <text class="suffix">元</text>
            </view>
          </u-form-item>

          <u-form-item :class="{active:curFocus==='discount'}" label="折扣" prop="discount" border="none"
            :borderBottom="false" ref="item4">
            <view class="input" :class="{active:curFocus==='discount',disabled:allowChangeDiscount===false}"
              @click.stop="onFocus('discount')">
              <text class="content"> {{goodsInfo.discount||''}}</text>
              <text class="suffix">%</text>
            </view>
          </u-form-item>
          <u-form-item :class="{active:curFocus==='_finalPrice'}" label="小计" prop="_finalPrice" border="none"
            :borderBottom="false" ref="item5">
            <view class="input disabled" :class="{active:curFocus==='_finalPrice'}">
              <text class="content"> {{goodsInfo._finalPrice||''}}</text>
              <text class="suffix">元</text>
            </view>
          </u-form-item>
        </u--form>
        <!--      <view class="bottom">
          <text>应付：</text>
          <text class="price">￥{{calcPrice||'0'}}</text>
        </view> -->
      </view>
      <view class="edit-goods-center-right">
        <u-number-keyboard :random="false" @change="changeNumber" @backspace="backspace" :mode="'number'"
          :dotDisabled="false">
        </u-number-keyboard>
      </view>
    </view>
    <view class="edit-goods-bottom">
      <button class="button normal" @click="cancel">取消</button>
      <button class="button" @click="confirm">确定</button>
    </view>
  </view>
</template>

<script>
  export default {
    name: "edit-goods-content",
    data() {
      return {
        curFocus: 'amount',
        goodsInfo: {
          cashier_setup: "",
          amount: 0,
          _finalPrice: 0, //小计
        },
      };
    },
    computed: {
      allowChangePrice() {
        return this.goodsInfo?.cashier_setup && this.goodsInfo?.cashier_setup.indexOf('改价') !== -1 ? true : false
      },
      allowChangeDiscount() {
        return this.goodsInfo?.cashier_setup && this.goodsInfo?.cashier_setup.indexOf('折扣') !== -1 ? true : false
      },
      calcPrice() {
        let res = this.goodsInfo?.amount ? this.goodsInfo?.amount * this.goodsInfo?.sale_price : 0
        return res.toFixed(2)
      }
    },
    props: {
      goods: {
        type: Object
      },
    },
    created() {
      this.goodsInfo = {
        _id: this.goods._id,
        goods_name: this.goods.goods_name,
        amount: this.goods.amount,
        discount: this.goods.discount || 100,
        _finalPrice: this.goods._finalPrice, // 消极
        sale_price: this.goods.sale_price, //现售价
        _origin_price: this.goods?._origin_price || this.goods.sale_price || 0, //原售价
        goods_price: this.goods?._origin_price || this.goods.sale_price || 0, //原售价
        scribing_price: this.goods.sale_price || this.goods.scribing_price, // 划线价
        goods_stock: this.goods.goods_stock,
        cashier_setup: this.goods.cashier_setup,
        minimum_price: this.goods.minimum_price, //最低售价
        allow_min_sales_price: this.goods.allow_min_sales_price, //低于最低售价 允许/不允许
      }
      this.goodsInfo.updateRecord = {
        amount: [],
        scribing_price: [], //划线价
        sale_price: [], //售价
        discount: [], //折扣
      }
      if (this.goods.is_temporary_goods === '是') {
        this.curFocus = 'sale_price'
      }
    },
    methods: {
      onFocus(e) {
        this.curFocus = e
      },
      backspace() {
        if (this.curFocus) {
          let newVal = this.goodsInfo[this.curFocus]
          console.log(newVal);
          if (newVal) {
            newVal += ''
            newVal = newVal.slice(0, newVal.length - 1)
            this.$set(this.goodsInfo, this.curFocus, newVal)
          }
          this.calcFinalPrice()
        }
      },
      changeNumber(e) {
        let val = this.goodsInfo[this.curFocus] + ''
        if (e === '.' && val && val.indexOf('.') > -1) {
          uni.showToast({
            title: '无效输入',
            icon: 'none'
          })
          return
        }
        let newVal = `${val}${e}`
        if (newVal && newVal.indexOf('.') > -1) {
          if (this.curFocus === 'amount') {
            uni.showToast({
              title: '数量不能输入小数',
              icon: 'none'
            })
            return
          }
          const index = newVal.indexOf('.')
          if (newVal.split('.')[1].length > 2) {
            uni.showToast({
              title: '小数点后最多只能输入两位...',
              icon: 'none'
            })
          }
          newVal = newVal.slice(0, index + 3)
        }
        if (typeof newVal === 'string' && newVal && newVal.lastIndexOf('.') === newVal.length - 1) {

        } else {
          if (typeof newVal === 'string' && newVal.length > 1 && newVal.indexOf('.') == -1) {
            newVal = Number(newVal)
          }
        }
        if (this.curFocus) {
          console.log(newVal, ',newVal');
          this.$set(this.goodsInfo, this.curFocus, newVal)
        }
        this.calcFinalPrice()
      },
      calcFinalPrice() {
        if (['discount', 'amount'].includes(this.curFocus)) {
          if (this.goods.is_temporary_goods == '是') {
            this.goodsInfo._finalPrice = Number(Number(this.goodsInfo.sale_price * this.goodsInfo.amount).toFixed(2))
            this.$nextTick(() => {

              const discount = this.goodsInfo.discount || 0
              const amount = this.goodsInfo.amount || 1
              if (this.curFocus === 'amount') {
                let salePrice = this.goodsInfo.sale_price * discount / 100;
                this.goodsInfo._finalPrice = Number(Number(salePrice * amount).toFixed(2))
              } else {
                this.goodsInfo._finalPrice = Number(Number(this.goodsInfo.sale_price * discount * amount / 100)
                  .toFixed(2))
              }
            })
            return
          }
          this.$nextTick(() => {
            const discount = this.goodsInfo.discount || 0
            const amount = this.goodsInfo.amount || 1
            let salePrice = Number(this.goodsInfo._origin_price * discount / 100)
            this.goodsInfo.sale_price = Number(salePrice)
            this.goodsInfo._new_sale_price = Number(salePrice)
            this.goodsInfo._finalPrice = Number(Number(salePrice * amount).toFixed(2))
          })
        } else if (['sale_price'].includes(this.curFocus)) {
          let salePrice = Number(this.goodsInfo.sale_price)
          this.goodsInfo._new_sale_price = salePrice
          const amount = this.goodsInfo.amount || 1
          this.goodsInfo.discount = parseInt((salePrice / this.goodsInfo._origin_price) * 100)
          this.goodsInfo._finalPrice = Number(Number(salePrice * amount).toFixed(2))
          if (this.goods.is_temporary_goods == '是') {
            this.goodsInfo.discount = 100
          }
        }
      },
      cancel() {
        if (!Number(this.goodsInfo.sale_price) && Number(this.goodsInfo.sale_price) !== 0 && this.goods
          .is_temporary_goods !== '是') {
          uni.showToast({
            title: '请输入商品价格',
            icon: 'none'
          })
          return
        }
        this.$emit('cancel')
      },
      confirm() {
        if (!Number(this.goodsInfo.sale_price) && Number(this.goodsInfo.sale_price) !== 0) {
          uni.showToast({
            title: '请输入商品价格',
            icon: 'none'
          })
          return
        }
        this.goodsInfo.sale_price = Number(this.goodsInfo.sale_price)
        if (this.goods.is_temporary_goods == '是' && this.goodsInfo.discount) {
          this.goodsInfo.sale_price = Number(this.goodsInfo.sale_price * this.goodsInfo.discount / 100)
        }
        this.goodsInfo._origin_price = Number(this.goodsInfo._origin_price)
        this.goodsInfo.goods_price = Number(this.goodsInfo.goods_price)
        const amount = this.goodsInfo.amount || 1
        let salePrice = Number(this.goodsInfo.sale_price);
        if (this.goodsInfo.allow_min_sales_price === '不允许' && this.goodsInfo
          .minimum_price &&
          salePrice < this.goodsInfo.minimum_price) {
          uni.showToast({
            title: '商品售价不能低于设置的最低售价',
            icon: 'none'
          })
          salePrice = this.goodsInfo.minimum_price;
          this.goodsInfo.discount = parseInt((salePrice / this.goodsInfo
            ._origin_price) * 100)
          this.goodsInfo.sale_price = Number(salePrice)
          this.goodsInfo._finalPrice = Number(Number(salePrice * amount).toFixed(2))
          return
        }
        const diffGoodsInfo = this.diffGoodsInfo()
        console.log(diffGoodsInfo);
        if (!this.goodsInfo.amount) {
          uni.showToast({
            title: '请输入商品数量',
            icon: 'none'
          })
          return
        }
        if (this.goodsInfo.amount==0) {
          uni.showToast({
            title: '商品数量不能为0',
            icon: 'none'
          })
          return
        }
        this.$emit('confirm', {
          ...this.goodsInfo,
          diff: diffGoodsInfo
        })
      },
      diffGoodsInfo() {
        const diffArr = ['amount', '_finalPrice', 'discount', 'sale_price']
        const result = {
          _updateTime: this.dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
        diffArr.forEach(key => {
          if (this.goods[key] !== this.goodsInfo[key]) {
            result[key] = {
              new: Number(this.goodsInfo[key]),
              old: Number(this.goods[key]),
            }
          }
          // this.goodsInfo[`_${key}updateRecord`] = [result[key]] || []
        })
        return result
      },
    },
  }
</script>

<style lang="scss" scoped>
  .edit-goods {
    display: flex;
    flex-direction: column;
    // height: 85rem;
    width: 110rem;
    border-radius: 2rem;
    padding: 2rem;

    &-center {
      display: flex;
      flex: 1;
      padding: 2rem 0;

      &-left {
        width: 50rem;
        border: 1px solid #E5E5E5;
        border-radius: 1rem;
        height: 100%;
        padding: 2rem;
        display: flex;
        flex-direction: column;

        .u-form {
          flex: 1;

          ::v-deep .u-form-item__body {
            padding: 1rem 0 0 0;
          }
        }

        .input {
          display: flex;
          align-items: center;
          width: 100%;
          border: 1px solid #dadbde;
          height: 6rem;
          border-radius: 1rem;
          padding: 1rem 2rem !important;
          font-size: 2.4rem;
          color: #000;

          &.disabled {
            background-color: #F5F5F5;
            color: #999;
          }

          &.active {
            border-color: $retail-color-primary !important;
          }

          .content {
            flex: 1;
          }

          .suffix {
            border-left: 1px solid #dadbde;
            padding-left: 1.5rem;
            display: inline-block;
            width: 3rem;
            color: #333;
          }
        }

        .bottom {
          padding: 2rem;
          font-size: $retail-font-size-sm;

          .price {
            color: #FF5733;
            font-size: $retail-font-size-lg;
          }
        }

        ::v-deep .u-form-item__body__left__content__label {
          font-size: $retail-font-size-sm;
          padding: 0 2rem;
        }

        ::v-deep .active .u-border {
          border-color: $retail-color-primary !important;
        }

        ::v-deep .u-input {
          height: 6rem;
          border-radius: 1rem;
          padding: 1rem 2rem !important;

          .u-input__content,
          .uni-input-wrapper {
            font-size: 2.4rem;
          }

          .uni-input-wrapper {
            color: #666;
          }
        }
      }

      &-right {
        flex: 1;
        margin-left: 2rem;

        ::v-deep .u-keyboard {
          background-color: #fff;
          justify-content: flex-end;
          padding: 0;

          .u-keyboard__button-wrapper {
            box-shadow: none;
            margin: .6rem;
            border-radius: 1rem;
            overflow: hidden;
            border: 1px solid #E5E5E5;

            &:nth-child(1),
            &:nth-child(2),
            &:nth-child(3) {
              margin-top: 0;
            }

            &:nth-child(10),
            &:nth-child(11),
            &:nth-child(12) {
              margin-bottom: 0;
            }

            &:nth-child(3n) {
              margin-right: 0;
            }

            &:nth-child(3n+1) {
              margin-left: 0;
            }
          }
        }



        ::v-deep .u-keyboard__button-wrapper__button {
          // width: 14rem;
          // height: 11rem;
          background-color: #F7F7F7;

          .u-icon__icon,
          .u-keyboard__button-wrapper__button__text {
            /** 文本1 */
            font-size: 3.6rem;
            font-weight: 700;
            text-align: center;
            margin-right: 1.2rem;
          }
        }
      }
    }

    &-bottom {
      width: 100%;
      text-align: right;

      .button {
        min-width: 20rem;
        height: 7.5rem;
        line-height: 7.5rem;
        font-size: $retail-font-size-sm;
        margin-left: 2rem;

        &.normal {
          background-color: #F5F5F5;
          color: #333;
        }
      }

    }
  }
</style>
